#pragma once
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>

const char *filename = "./fifo";
const int gmode = 0600;
const int gforread = O_RDONLY;
const int gforwrite = O_WRONLY;

class Fifo
{
    int OpenFifo(int flag)
    {
        _fd = open(filename, flag);
        if(_fd == -1)
        {
            std::cout << "open error"<< std::endl;
            return _fd;
        }
        return _fd;
    }

public:
    Fifo() : _fd(-1)
    {
        umask(0);
        int i = mkfifo(filename, gmode);
        if (i == -1)
        {
            std::cout << "mkfifo error" << std::endl;
            return ;
        }
        std::cout << "mkfifo sucess" << std::endl;
    }

    bool Fifoforwrite()
    {
        OpenFifo(gforwrite);
        if(_fd < 0) return false;
        return true;
    }

    bool Fifoforread()
    {
        OpenFifo(gforread);
        if(_fd < 0) return false;
        return true;
    }

    int wait()
    {
        int num = 0;
        int i = read(_fd, &num, sizeof(num));
        if(i < 0)
        {
            return 2;
        }
        if(i < sizeof(num))
        {
            return 1;
        }
        return 0;
    }

    int signal()
    {
        int num = 1;
        int i = write(_fd, &num, sizeof(num));
        return i;
    }

    ~Fifo()
    {
        if(_fd >= 0)
        {
            close(_fd);
        }
        int i = unlink(filename);
        if(i < 0)
        {
            std::cout << "unlink error" << std::endl;
            return;
        }
        std::cout << "unlink sucess" << std::endl;
        
    }

private:
    int _fd;
};

Fifo fifo;